package cn.fanyamin.web.struts;

import java.sql.Timestamp;
import java.util.List;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.LazyValidatorForm;

import cn.fanyamin.business.ItemService;
import cn.fanyamin.business.TaskService;
import cn.fanyamin.domain.UserCategory;
import cn.fanyamin.domain.Item;
import cn.fanyamin.domain.Task;
import cn.fanyamin.domain.User;

public class ItemAction extends SecureBaseAction {
	private static Log logger = LogFactory.getLog(ItemAction.class);

	public ActionForward list(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
		ItemService itemService = getWebApp().getItemService();
		int itemType = NumberUtils.toInt(request.getParameter("itemType"));
		if(itemType==0) {
			itemType = NumberUtils.toInt((String)request.getAttribute("itemType"));
		}
		int categoryID = NumberUtils.toInt(request.getParameter("categoryID"));
        
		
		User user = getUserFromSession(request);
		
		Item item = new Item();
        item.setUserID(user.getUserID());
        item.setItemType(itemType);
        item.setCategoryID(categoryID);
        
		setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
		setItemTypes(request);
	    List<Item> itemList = itemService.findItems(item);
	    request.setAttribute("itemList", itemList);
		logger.info("itemList: " + itemList);
        return mapping.findForward("list");

	}
	
	public ActionForward create(ActionMapping mapping, ActionForm form,
	                            HttpServletRequest request, HttpServletResponse response) {
		ItemService itemService = getWebApp().getItemService();
		Item item = getItemFromForm(form);
		if(item == null) {
		    return mapping.findForward("failure");
		}
		User user = getUserFromSession(request);
		item.setUserID(user.getUserID());
		int itemID = itemService.create(item);
		item.setItemID(itemID);
		request.setAttribute("itemType", item.getItemType());
		logger.info("create item: " + item);
		return mapping.findForward("success");
		//return new ActionForward("item.htm?itemType=" + item.getItemType(),true);//redirect
	}
	
    private Item getItemFromForm(ActionForm form) {
		Item item = new Item();
		LazyValidatorForm itemForm = (LazyValidatorForm) form;

		item.setItemID(NumberUtils.toInt((String) itemForm.get("itemID")));
		item.setItemName(StringUtils.trim(""+itemForm.get("itemName")));	
		item.setItemType(NumberUtils.toInt((String) itemForm.get("itemType")));	
		item.setDescription(StringUtils.trim(""+ itemForm.get("description")));
		item.setCategoryID(NumberUtils.toInt((String)itemForm.get("categoryID")));

		return item;
	}

    public ActionForward retrieve(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        ItemService itemService = getWebApp().getItemService();
        LazyValidatorForm itemFrom = (LazyValidatorForm)form;
        int itemID = NumberUtils.toInt((String)itemFrom.get("itemID"));
        Item item = itemService.retrieve(itemID);
        request.setAttribute("item", item);
        return mapping.findForward("edit");
    }
    
    public ActionForward asTask(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
    	ItemService itemService = getWebApp().getItemService();
    	
    	int taskType = NumberUtils.toInt((String)request.getParameter("taskType"));
    	
    	String arrItemID[] = request.getParameterValues("itemID");
    	for (String strItemID : arrItemID) {
			int itemID = NumberUtils.toInt(strItemID);
			if (itemID > 0) {
				Item item = itemService.retrieve(itemID);
				TaskService taskService = getWebApp().getTaskService();
				Task task = new Task();
				task.setTaskName(item.getItemName());
				task.setTaskType(taskType);
				task.setDescription(item.getDescription());
				task.setDeadline(new Timestamp(
						System.currentTimeMillis() + 36000000));
				User user = getUserFromSession(request);
				task.setUserID(user.getUserID());
				taskService.create(task);
				itemService.delete(itemID);
			}
		}
    	return mapping.findForward("success");
    }
    
    public ActionForward finish(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
                                HttpServletResponse response) {
        ItemService itemService = getWebApp().getItemService();
        String strItemID = request.getParameter("itemID");

        int itemID = NumberUtils.toInt(strItemID);
        if (itemID > 0) {
            Item item = itemService.retrieve(itemID);
            TaskService taskService = getWebApp().getTaskService();
            Task task = new Task();
            task.setTaskName(item.getItemName());
            task.setDescription(item.getDescription());
            task.setDeadline(new Timestamp(System.currentTimeMillis() + 120000));
            task.setBeginTime(new Timestamp(System.currentTimeMillis()));
            task.setEndTime(new Timestamp(System.currentTimeMillis() + 120000));
            User user = getUserFromSession(request);
            task.setUserID(user.getUserID());
            taskService.create(task);
            itemService.delete(itemID);
        }

        return mapping.findForward("success");
    }
    
    public ActionForward asItem(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
    	ItemService itemService = getWebApp().getItemService();
    	int itemType = NumberUtils.toInt((String)request.getParameter("itemType"));
    	String arrItemID[] = request.getParameterValues("itemID");
    	for(String strItemID:arrItemID) {
	    	int itemID = NumberUtils.toInt(strItemID);
	    	if(itemID>0) {
	    		Item item = itemService.retrieve(itemID);
	    		item.setItemType(itemType);
	    		itemService.update(item);
	    	}
    	}
    	return mapping.findForward("success");
    }
    
    public ActionForward update(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        
        ItemService itemService = getWebApp().getItemService();
        Item item = getItemFromForm(form);
        itemService.update(item);
        //request.setAttribute("itemType", item.getItemType());
        logger.info("update item, item=" + item);
        //return new ActionForward("item.htm?itemType=" + item.getItemType(),true);//redirect
        return mapping.findForward("success");
    }
    
    public ActionForward delete(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        ItemService itemService = getWebApp().getItemService();
        LazyValidatorForm itemFrom = (LazyValidatorForm)form;
        int itemID = NumberUtils.toInt((String)itemFrom.get("itemID"));
        itemService.delete(itemID);
        int itemType = NumberUtils.toInt(request.getParameter("itemType"));
        //request.setAttribute("itemType", itemType);
        logger.info("delete item, itemID=" + itemID);
        return mapping.findForward("success");
        //return new ActionForward("item.htm?itemType=" + itemType,true);//redirect
    }
    
    public ActionForward add(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
    	logger.info("add item");
    	
    	setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
    	setItemTypes(request);
    	
    	return mapping.findForward("add");
    }
    
    public ActionForward edit(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        ItemService itemService = getWebApp().getItemService();
        LazyValidatorForm itemFrom = (LazyValidatorForm)form;
        int itemID = NumberUtils.toInt((String)itemFrom.get("itemID"));
        Item item = itemService.retrieve(itemID);
        request.setAttribute("item", item);
        
        setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
        setItemTypes(request);
        return mapping.findForward("edit");
    }
}
